/**
 * Created by isoft-work 5 on 11/15/14.
 */
//<div id="check_error_email" class="s-error msg">Địa chỉ email không hợp lệ</div>
//<div id="check_error_pass" class="s-error msg">Mục yêu cầu</div>
//error
$(document).ready(function(){
   bindEventLogin();
});

function bindEventLogin() {

   ISS.EVENT.bindEvent('#LoginForm_submit', 'click', function () {
      clearValidate();
      if(validate()){
         sendInfo();
      }
   });

   ISS.EVENT.bindEvent('#LoginForm_password', 'keyup', function (e) {
      if(e.keyCode === CONSTANT.KEY_CODE.ENTER) {
         clearValidate();
         if(validate()){
            sendInfo();
         }
      }
   });
}

function clearValidate() {
   ISS.DOM.html('#check_error_email', '');
   ISS.DOM.html('#check_error_pass', '');

   ISS.DOM.removeClass('#LoginForm_email', 'error');
   ISS.DOM.removeClass('#LoginForm_password', 'error');
}

function sendInfo() {
   var login = {};
//   get info
   login.email = ISS.DOM.getVal('#LoginForm_email');
   login.pass = ISS.DOM.getVal('#LoginForm_password');
   login.stayLogged = ISS.DOM.getVal('#LoginForm_stayLogged');
//   request
   ISS.BACKEND.request({
      url: '../../service/header/login',
      headers: {
         'Accept': 'application/json',
         'Content-Type': 'application/json'
      },
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(login),
      success: function (data) {
         var responseContent = data.responseObject;
         if(responseContent){
            loginComplete(responseContent);
         }
         else {
            loginError();
         }
      }
   });
}

function loginComplete(login) {
  if(login.stayLogged) {
     ISS.COOKIE.setCookie('userName', login.email, 365);
     ISS.WINDOW.location('');
  }
  else {
     ISS.SESSION.setSession('userName', login.email);
     ISS.WINDOW.location('');
  }
}

function loginError() {
   ISS.DOM.html('#check_error_pass', 'Tên truy cập hoặc mật khẩu không đúng');
   ISS.DOM.addClass('#LoginForm_password', 'error');
}

function validate() {
   var email, pass, result;
   email = ISS.DOM.getVal('#LoginForm_email');
   pass = ISS.DOM.getVal('#LoginForm_password');
   if(!email) {
      ISS.DOM.html('#check_error_email', 'Mục yêu cầu');
      ISS.DOM.addClass('#LoginForm_email', 'error');
      result = false;
   }

   if(!pass) {
      ISS.DOM.html('#check_error_pass', 'Mục yêu cầu');
      ISS.DOM.addClass('#LoginForm_password', 'error');
      result = false;
   }

   if(email && pass) {
      if(!ISS.VALIDATION.validateEmail(email, true)) {
         ISS.DOM.html('#check_error_email', 'Địa chỉ email không hợp lệ');
         ISS.DOM.addClass('#LoginForm_email', 'error');
         result = false;
      }
      else {
         result = true;
      }
   }
   return result;
}
